<?php


namespace Biz\model\advertisement;


class MHhzDepartmentMenu extends MBaseDbModel
{
    const _CONFIG_FILE_ = 'db_position';

    const _CONFIG_SELECT_ = 'db_position';

    const _DATABASE_ = 'hhz_position';

    const _TABLE_NAME = 'hhz_department_menu';

    const IS_DELETED_YES = 1;

    const IS_DELETED_NO = 0;

    public static function updateDepartmentMenu($departmentId, $menuCodes)
    {
        if (!$departmentId) {
            return;
        }

        $existedMenuCodes = self::getMenuCodesByDepartmentId($departmentId);

        $needToDelete = array_diff($existedMenuCodes, $menuCodes);
        if ($needToDelete) {
            $where = [
                'department_id' => $departmentId,
                'menu_code' => $needToDelete,
            ];
            self::update(['is_deleted' => self::IS_DELETED_YES, 'deleted_at' => date('Y-m-d H:i:s')], $where);
        }

        $needToInsert = array_diff($menuCodes, $existedMenuCodes);
        if ($needToInsert) {
            $insertData = [];

            foreach ($needToInsert as $d) {
                $insertData[] = [
                    'department_id' => $departmentId,
                    'menu_code' => $d,
                ];
            }

            self::insert($insertData);
        }
    }

    public static function getMenuCodesByDepartmentId($departmentId)
    {
        if (!$departmentId) {
            return [];
        }

        return self::select("menu_code", [
            'department_id' => $departmentId,
            'is_deleted' => self::IS_DELETED_NO,
        ]);
    }
}
